/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kylingroup.Desktop;

import com.kylingroup.Desktop.Database.DBConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;

/**
 * FXML Controller class
 *
 * @author kylin
 */
public class PaneDatabaseController implements Initializable {
    @FXML
    private Button btncreate;
    @FXML
    private TextArea resultarea;
    @FXML
    private TextArea statearea;
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        String dsql="create table tbplugins("+
        "id integer primary key,"+
        "autoload string,"+
        "name string,"+
        "location string,"+
        "clazz string unique,"+
        "category string,"+
        "version string,"+
        "description string,"+
        "author string,"+
        "email string)";
        statearea.setText(dsql);
        
        DBConnection dbconn=MainFrame.dbconn;
        
        btncreate.setOnAction((ActionEvent event) -> {
            Connection conn=dbconn.getConnection();
            String sql=statearea.getText().trim();
            String result="result";
            result=createTable(sql,conn);
            resultarea.appendText("result:\n"+result+"\n"+new Date().toString()+"\n");
        });
    }    
    public String createTable(String sql,Connection conn){
        String result=null;
        Statement statement=null;
        
        try {
            statement=conn.createStatement();
            statement.executeUpdate(sql);
            result="table has been successfully created.";
            
        } catch (SQLException ex) {
            result="failed to exacute sql statement! please check your statement and try again.\n";
            result+=ex.toString();
        }finally{
            try{
                if(statement!=null){
                    statement.close();
                }
                if(conn!=null){
                    conn.close();
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        return result;
    }
}
